package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("登录失败");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果    (empId)存
        request.getSession().setAttribute("empId",emp.getId());
        return R.success(emp);
    }
    /**
     * 退出功能
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        log.info("退出登录");
        session.removeAttribute("empId");
        return R.success(null);
    }

    /**
     * 新增员工信息
     * @param employee
     * @return
     */
    @PostMapping
    public R save(HttpSession session,@RequestBody Employee employee){
        //1.接收数据
        log.info("emp:{}",employee);
        //2.封装数据(status\字段)
        employee.setStatus(1);
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        employee.setCreateUser((Long) session.getAttribute("empId"));
//        employee.setUpdateUser((Long) session.getAttribute("empId"));
        //3.数据库新增操作
        boolean b = employeeService.save(employee);
        //4.给出响应
        return b?R.success(null):R.error("新增失败");
    }
    //@PathVariable --/1
    //@RequestBody  --/json
    //@RequestParam 可省略

    /**
     * 分页查询
     * @param page  第几页
     * @param pageSize 每页大小
     * @param name 条件查询
     * @return 返回数据
     */
    @GetMapping("/page")
    public  R page(Integer page,Integer pageSize,String name){
        //1.接收参数
        log.info("page: {},pageSize:{},name:{}",page,pageSize,name);
        //2.构建分页条件（当前页，每页大小）
        IPage<Employee> emloyeePage = new Page<>(page, pageSize);
        //3.构建查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Employee::getName,name);//条件模糊查询
        wrapper.orderByAsc(Employee::getUpdateTime);//按照修改时间排序
        //4.开始查找
        employeeService.page(emloyeePage, wrapper);
        //5.相应数据
        return R.success(emloyeePage);
    }
    @PutMapping
    public R update(HttpSession session,@RequestBody Employee employee){
        //1.接收参数
        log.info("修改的emp为：{}",employee);
//        //2.维护字段修改人，修改时间
//        employee.setUpdateUser((Long) session.getAttribute("empId"));
//        employee.setUpdateTime(LocalDateTime.now());
        //3.修改
        boolean b =employeeService.updateById(employee);

        return b?R.success("操作成功"):R.error("操作失败");
    }

    /**
     * 根据id查询用户信息
     * @param id    用户id
     * @return  返回数据
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        //1.接收参数
        log.info("id:{}",id);
        //2.根据id查询用户信息
        Employee employee = employeeService.getById(id);
        //3.返回数据
        return R.success(employee);
    }
}
